/**
 * @Title:  AttentionDynamicsActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2015-12-7 上午10:20:14 
 * @version:  V1.0 
 */

package artid.com.arttogo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.umeng.socialize.utils.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.ShootAdapter;
import artid.com.arttogo.bean.ArtList;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.fragment.BaseFragment;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableListView;

/**
 * 主页查询页面
 */
public class SearchActivity extends BaseFragment implements OnClickListener {
	View mView;
	private Context mContext;
	private PullableListView mListView;
	private ShootAdapter adapter;
	ImageView mimgMirrorCenter, mimgMirrorLeft;
	EditText meditSearch;
	// TextView text_
	View viewSearch;
	TextView textSearchTag, textcancel;
	Boolean isSearching = false;
	LinearLayout linearSearch;
	View viewTextTag, viewTagList;
	TextView serarchTag;
	View viewQb, viewWjz, viewYjz, viewHide;
	String strReqStatus = "0";

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)
	 */
	int anmiSpeed = 400;
	PullToRefreshLayout mPullLayout;
    List<ArtList> list_bean;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.activity_search, null);
		mContext = getActivity();
		textcancel = (TextView) mView.findViewById(R.id.searchcancel);
		textcancel.setOnClickListener(this);
		textcancel.setVisibility(View.GONE);
		linearSearch = (LinearLayout) mView.findViewById(R.id.linearLayout1);
		textSearchTag = (TextView) mView.findViewById(R.id.text_search_tag);
		viewSearch = (View) mView.findViewById(R.id.relasearch);
		viewSearch.setOnClickListener(this);
		mListView = (PullableListView) mView.findViewById(R.id.listivew);
		mimgMirrorCenter = (ImageView) mView.findViewById(R.id.imageView1);
		mimgMirrorLeft = (ImageView) mView.findViewById(R.id.imageView2);
		meditSearch = (EditText) mView.findViewById(R.id.editText1);
		meditSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		meditSearch.setVisibility(View.GONE);
		meditSearch
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					public boolean onEditorAction(TextView v, int actionId,
												  KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_SEARCH
								|| (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
							pageindex = 1;
							reqData(meditSearch.getText().toString());
							onClick(textcancel);
							return true;
						}
						return false;
					}
				});
		mimgMirrorLeft.setVisibility(View.GONE);
		viewTextTag = (View) mView.findViewById(R.id.view_search_tag);
		viewTextTag.setOnClickListener(this);
		viewTagList = (View) mView.findViewById(R.id.view_search_tag_list);
		serarchTag = (TextView) mView.findViewById(R.id.textsearch);
		viewQb = (View) mView.findViewById(R.id.text_search_qb);
		viewQb.setOnClickListener(this);
		viewYjz = (View) mView.findViewById(R.id.text_search_yjz);
		viewYjz.setOnClickListener(this);
		viewWjz = (View) mView.findViewById(R.id.text_search_wjz);
		viewWjz.setOnClickListener(this);
		mPullLayout = (PullToRefreshLayout) mView
				.findViewById(R.id.refresh_view);
		mPullLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				pageindex = 1;
				reqData(meditSearch.getText().toString());
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// pullToRefreshLayout.setBottomDismiss();
				pageindex++;
				reqData(meditSearch.getText().toString());
			}
		});
		viewHide = (View) mView.findViewById(R.id.view_hide);
		viewHide.setOnClickListener(this);
		ids = new ArrayList<String>();
		return mView;
	}

	int pageindex = 1, pagesize = 10;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		reqData("");
	}
	ArrayList<String> ids ;
	void reqData(String keyword) {
		VolleyBasic.getInstance(getActivity()).post(
				Cache.allArtList,
				VolleyMap.getInstance().allArtList(String.valueOf(pageindex),
						keyword, String.valueOf(pagesize), "2"),
				ArtList.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						JSONObject jsonString = vd.getObj();
						JSONArray jsonArray = jsonString.optJSONArray("data");
						mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
                        list_bean = (List<ArtList>) vd.getList();
						if (list_bean.isEmpty()) {
//							Config.showTip(getActivity(), "无数据");
							return;
						}
						if (pageindex != 1) {
							for (int i = 0; i < list_bean.size(); i++) {
								ids.add(list_bean.get(i).getArt_id());
							}
							
							adapter.adddata(list_bean);
							mListView.setOnItemClickListener(itemListener(ids));
							return;
						}
						ids = new ArrayList<String>();
						for (int i = 0; i < list_bean.size(); i++) {
							ids.add(list_bean.get(i).getArt_id());
						}
						adapter = new ShootAdapter(getActivity());
						adapter.setdata(list_bean);
						mListView.setAdapter(adapter);
						mListView.setOnItemClickListener(itemListener(ids));
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						mPullLayout.loadmoreFinish(mPullLayout.FAIL);
					}
				});
	}

	OnItemClickListener itemListener(final ArrayList<String> list) {
		return new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						CollectionDetailPagerActivity.class);
				intent.putStringArrayListExtra("id", list);
				intent.putExtra("index", position);
                if(list_bean.get(position).getIs_type()==2) {
                    //机构
                    intent.putExtra("isOrg", false);
                }else{
                    //艺术家
                    intent.putExtra("isOrg", true);
                }
				startActivity(intent);


			}
		};
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.view_search_tag:
			if (viewTagList.getVisibility() == View.GONE) {
				viewTagList.setVisibility(View.VISIBLE);
			} else {
				viewTagList.setVisibility(View.GONE);
			}

			break;
		case R.id.relasearch:
			if (!isSearching) {
				viewHide.setVisibility(View.VISIBLE);
				isSearching = true;
				openInput();
				// Animation translateAnimation2 = new
				// TranslateAnimation(VeDate.dip2px(getActivity(), 160),0f,
				// 0f, 0f);
				// translateAnimation2.setDuration(anmiSpeed);
				// mimgMirrorLeft.setAnimation(translateAnimation2);
				serarchTag.setVisibility(View.GONE);
				mimgMirrorLeft.setVisibility(View.VISIBLE);
				mimgMirrorCenter.setVisibility(View.INVISIBLE);
				viewTextTag.setVisibility(View.GONE);

				Animation scaleAnimation = new ScaleAnimation(1f, 0.8f, 1f, 1f,
						1f, 1f);
				scaleAnimation.setDuration(anmiSpeed);
				scaleAnimation.setFillAfter(true);
				scaleAnimation
						.setAnimationListener(new Animation.AnimationListener() {

							@Override
							public void onAnimationStart(Animation arg0) {
								// TODO Auto-generated method stub
								serarchTag.setVisibility(View.GONE);
							}

							@Override
							public void onAnimationRepeat(Animation arg0) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onAnimationEnd(Animation arg0) {
								// TODO Auto-generated method stub
								meditSearch.setVisibility(View.VISIBLE);
								textcancel.setVisibility(View.VISIBLE);
								meditSearch.setFocusable(true);
								meditSearch.setFocusableInTouchMode(true);
								meditSearch.requestFocus();

							}
						});
				linearSearch.setAnimation(scaleAnimation);

			}
			break;

		case R.id.searchcancel:
			if (isSearching) {
				isSearching = false;

				// Animation translateAnimation2 = new
				// TranslateAnimation(0f,VeDate.dip2px(getActivity(), 160),
				// 0f, 0f);
				// translateAnimation2.setDuration(500);
				// mimgMirrorLeft.setAnimation(translateAnimation2);
				mimgMirrorCenter.setVisibility(View.GONE);
				mimgMirrorLeft.setVisibility(View.GONE);
				meditSearch.setVisibility(View.GONE);
				viewTextTag.setVisibility(View.GONE);
				viewTagList.setVisibility(View.GONE);
				textSearchTag.setVisibility(View.VISIBLE);
				Animation scaleAnimation = new ScaleAnimation(0.8f, 1f, 1f, 1f,
						1f, 1f);
				scaleAnimation.setDuration(500);
				scaleAnimation.setFillAfter(true);
				linearSearch.setAnimation(scaleAnimation);
				textcancel.setVisibility(View.GONE);
				serarchTag.setVisibility(View.VISIBLE);
			}
			break;

		case R.id.text_search_qb:
			pageindex = 1;
			strReqStatus = "0";
			reqData(meditSearch.getText().toString());
			textSearchTag.setText("全部");
			viewTagList.setVisibility(View.GONE);
			break;
		case R.id.text_search_wjz:
			pageindex = 1;
			strReqStatus = "1";
			reqData(meditSearch.getText().toString());
			viewTagList.setVisibility(View.GONE);
			textSearchTag.setText("未鉴证");
			break;
		case R.id.text_search_yjz:
			pageindex = 1;
			strReqStatus = "2";
			reqData(meditSearch.getText().toString());
			textSearchTag.setText("已鉴证");
			viewTagList.setVisibility(View.GONE);
			break;
		case R.id.view_hide:
			closeInputMethod();
			break;
		default:
			break;
		}
	}

	void openInput() {
		InputMethodManager m = (InputMethodManager) meditSearch.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

	}

	void closeInputMethod() {
		viewHide.setVisibility(View.GONE);
		try {
			InputMethodManager inputMethodManager = (InputMethodManager) mContext
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(getActivity()
					.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
			// TODO: handle exception
			Log.d("", "关闭输入法异常");
		}
	}

}
